package com.lixh.sdk.base.http

import com.jakewharton.retrofit2.adapter.kotlin.coroutines.CoroutineCallAdapterFactory
import okhttp3.Cookie
import okhttp3.CookieJar
import okhttp3.HttpUrl
import okhttp3.Interceptor
import retrofit2.Converter
import retrofit2.Retrofit


object ApiFactory {
    private val cookieStore: HashMap<String, List<Cookie>> = HashMap()

    fun <T> createApi(
        baseUrl: String,
        t: Class<T>,
        factory: Converter.Factory,
        vararg interceptor: Interceptor,
    ): T =
        Retrofit.Builder()
            .addConverterFactory(factory)
            .addCallAdapterFactory(CoroutineCallAdapterFactory())
            .baseUrl(baseUrl)
            .client(ClientFactory.client().apply {
                cookieJar(object : CookieJar {
                    override fun loadForRequest(url: HttpUrl): List<Cookie> {
                        return cookieStore[url.host] ?: ArrayList()
                    }

                    override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
                        cookieStore[url.host] = cookies;
                    }

                })
                interceptor.forEach {
                    addInterceptor(it)
                }
            }.build()).build().create(t)

}